/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imp.reciever.process;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author rodrigo.estrada
 */
public class Zip extends ProcessReciever{
    
        
    public Zip(){
        super(null, null);
    }

    @Override
    public void action() throws Exception {
        while (fileName.equals("")) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException interruptedException) {}
        }
        stop = false;
        String fileNameZip;
        byte[] buf = new byte[BUFFER_SIZE];
        ZipOutputStream zos;
        zos = new ZipOutputStream(outputStream);
        String[] split = fileName.split(SEPARATOR);
        fileNameZip = new String(split[split.length - 2] + ".zip");
        this.notifyStop(fileNameZip);
        while(true){
            int len;
            split = fileName.split(SEPARATOR);
            System.out.println("Comprimiendo: " + fileName);
            ZipEntry zipEntry = new ZipEntry(split[split.length-1]); 
            zos.putNextEntry(zipEntry);
            while ((len = inputStream.available()) > -1) {
                if (len<= 0) {
                    if (stop) {
//                        System.out.println("disponible: " + inputStream.available());
                        break;
                    }
                }
                len = inputStream.read(buf);
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            stop = false;
            if (fileName == null) {
                System.out.println("Termino de comprimir");
                zos.close();
                super.notifyStop(null);
                outputStream.close();
                return;
            }
        }
    }

    
    @Override
    public boolean isInputReady() {
        if (inputStream != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isOutputReady() {
        if (outputStream != null) {
            return true;
        } else {
            return false;
        }
    }
    
}
